package com.lin.controller.client;

import com.lin.entity.Comment;
import com.lin.entity.ResponseData;
import com.lin.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author lin
 */
@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;

    @RequestMapping("/comments/publish")
    @ResponseBody
    public ResponseData publish ( HttpServletRequest request, @RequestParam("aid") Integer aId, @RequestParam("text") String content ) {
        Date date = new Date();


        Comment comment = new Comment();
        //文章id
        comment.setArticleId(aId);

        //评论时间
        comment.setCreated(date);

        //评论人的ip地址
        //通过 request 的 getRemoteAddr 方法获取 当前ip地址
        String remoteAddr = request.getRemoteAddr();
        //赋值给comment 对象
        comment.setIp(remoteAddr);

        //评论内容
        comment.setContent(content);

        //评论状态
        comment.setStatus("approved");

        //通过 安全框架获取当前用户
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //评论作者的用户名
        comment.setAuthor(user.getUsername());
        commentService.pushComment(comment);
        return ResponseData.OK();
    }
}
